package com.next.aappublicapp.handlers;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle;

import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubeStandalonePlayer;
import com.next.aap.client.BaseItem;
import com.next.aap.client.NewsItem;
import com.next.aap.client.VideoItem;
import com.next.aappublicapp.PagerViewActivity;

public class ItemClickHandlerImpl<T extends BaseItem> implements
		ItemListClickHandler<T> {

	private Context context;
	public static final int REQ_START_STANDALONE_PLAYER = 1;
	public static final int REQ_RESOLVE_SERVICE_MISSING = 2;

	public ItemClickHandlerImpl(Context context) {
		this.context = context;
	}

	public static final String DEVELOPER_KEY = "AIzaSyC5zoNmY0IP-pe-hTBpVyeafXObMqdNeH8";

	@Override
	public void ItemClicked(int position, T item, List<T> items) {
		if (item instanceof NewsItem) {
			Intent intent = new Intent(context, PagerViewActivity.class);
			Bundle bundle = new Bundle();
			bundle.putSerializable(PagerViewActivity.ARGS_ITEM_LIST,
					(ArrayList<? extends BaseItem>) items);
			bundle.putInt(PagerViewActivity.ARGS_ITEM_POSITION, position);
			intent.putExtra(PagerViewActivity.ARGS_BUNDLE, bundle);
			context.startActivity(intent);
		}
		if (item instanceof VideoItem) {
			EasyTracker.getTracker().sendView("Video View");
			VideoItem videoItem = (VideoItem) item;

			Intent lVideoIntent = YouTubeStandalonePlayer.createVideoIntent(
					(Activity) context, DEVELOPER_KEY, videoItem.getVideoId(),
					0, true, false);
			if (lVideoIntent != null) {
				if (canResolveIntent(context,lVideoIntent)) {
					((Activity) context).startActivityForResult(lVideoIntent,
							REQ_START_STANDALONE_PLAYER);
				} else {
					// Could not resolve the intent - must need to install or
					// update the YouTube? API service.
					YouTubeInitializationResult.SERVICE_MISSING.getErrorDialog(
							(Activity) context, REQ_RESOLVE_SERVICE_MISSING)
							.show();
				}
			}
		}
	}

	public static boolean canResolveIntent(Context context, Intent intent) {
		List<ResolveInfo> resolveInfo = context.getPackageManager()
				.queryIntentActivities(intent, 0);
		return resolveInfo != null && !resolveInfo.isEmpty();
	}
}
